package com.jx.interceptor;

import com.jx.entity.User;
import com.jx.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Author Mr.Liu
 * @Date 2021/10/14 8:39
 * @Version 1.0
 */
public class InterceptorTest implements HandlerInterceptor {
    /**
     * 调用控制器方法之前之前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("拦截器执行：preHandle方法");
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("login_user");
        if(user == null){
            request.getRequestDispatcher("/login/loginForm").forward(request,response);

            return false;
        }else{
            return true;
        }

    }

    /**
     * 控制器方法调用之后，页面渲染之前执行
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器执行：postHandle方法");
    }

    /**
     * 试图渲染之后给用户结果的时候执行
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("拦截器执行：afterCompletion方法");
    }
}
